#include "notificationmanager.h"
#include <QtWidgets/QApplication>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QSystemTrayIcon>
#include <QtCore/QDebug>

NotificationManager::NotificationManager(QObject *parent)
    : QObject(parent)
    , m_trayIcon(nullptr)
    , m_trayIconMenu(nullptr)
    , m_trayEnabled(true)
{
    if (QSystemTrayIcon::isSystemTrayAvailable() && m_trayEnabled) {
        createTrayIcon();
    }
}

NotificationManager::~NotificationManager()
{
    if (m_trayIcon) {
        delete m_trayIcon;
    }
}

void NotificationManager::showNotification(const QString &title, const QString &message, int timeout)
{
    // 首先尝试使用系统托盘通知
    if (m_trayIcon && m_trayIcon->isVisible()) {
        showMessage(title, message, QSystemTrayIcon::Information, timeout);
    } else {
        // 如果系统托盘不可用，使用弹窗通知
        QMessageBox *msgBox = new QMessageBox(QMessageBox::Information, title, message, QMessageBox::Ok);
        msgBox->setAttribute(Qt::WA_DeleteOnClose);
        msgBox->setWindowModality(Qt::NonModal);
        msgBox->show();
    }
}

void NotificationManager::setTrayEnabled(bool enabled)
{
    m_trayEnabled = enabled;
    
    if (enabled && QSystemTrayIcon::isSystemTrayAvailable()) {
        if (!m_trayIcon) {
            createTrayIcon();
        }
        if (m_trayIcon) {
            m_trayIcon->show();
        }
    } else if (m_trayIcon) {
        m_trayIcon->hide();
    }
}

bool NotificationManager::isTrayAvailable() const
{
    return QSystemTrayIcon::isSystemTrayAvailable() && m_trayEnabled && m_trayIcon;
}

void NotificationManager::onDownloadFinished(const QString &fileName)
{
    showNotification("下载完成", QString("文件 %1 已下载完成").arg(fileName));
}

void NotificationManager::onDownloadError(const QString &fileName, const QString &error)
{
    showNotification("下载错误", QString("文件 %1 下载失败: %2").arg(fileName).arg(error));
}

void NotificationManager::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::Trigger) {
        // 点击托盘图标时显示主窗口
        emit qobject_cast<QApplication*>(QApplication::instance())->focusChanged(
            nullptr, QApplication::activeWindow());
    }
}

void NotificationManager::createTrayIcon()
{
    m_trayIcon = new QSystemTrayIcon(this);
    m_trayIcon->setIcon(QIcon(":/icons/app.png")); // 使用应用程序图标
    
    m_trayIconMenu = new QMenu();
    QAction *quitAction = m_trayIconMenu->addAction("退出");
    connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);
    
    m_trayIcon->setContextMenu(m_trayIconMenu);
    m_trayIcon->show();
    
    connect(m_trayIcon, &QSystemTrayIcon::activated, 
            this, &NotificationManager::onTrayIconActivated);
}

void NotificationManager::showMessage(const QString &title, const QString &message, 
                                     QSystemTrayIcon::MessageIcon icon, int timeout)
{
    if (m_trayIcon && m_trayIcon->isVisible()) {
        m_trayIcon->showMessage(title, message, icon, timeout);
    }
}